<template>
  <div class="layout-judge-container">
    <!-- 搜索区域 -->
    <div class="search-panel">
      <div class="search-row">
        <div class="search-item">
          <span class="label">时间</span>
          <el-date-picker v-model="searchParams.dateRange" type="daterange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" class="custom-date-picker" />
        </div>
        <div class="search-item range-item">
          <span class="label">成品厚度</span>
          <el-input v-model="searchParams.prodThicknessMin" placeholder="最小值" class="range-input" />
          <span class="separator">-</span>
          <el-input v-model="searchParams.prodThicknessMax" placeholder="最大值" class="range-input" />
        </div>
        <div class="search-item range-item">
          <span class="label">成品宽度</span>
          <el-input v-model="searchParams.prodWidthMin" placeholder="最小值" class="range-input" />
          <span class="separator">-</span>
          <el-input v-model="searchParams.prodWidthMax" placeholder="最大值" class="range-input" />
        </div>
         <div class="search-item range-item">
          <span class="label">原料厚度</span>
          <el-input v-model="searchParams.materialThicknessMin" placeholder="最小值" class="range-input" />
          <span class="separator">-</span>
          <el-input v-model="searchParams.materialThicknessMax" placeholder="最大值" class="range-input" />
        </div>
        <div class="search-item">
          <span class="label">钢种</span>
          <el-select v-model="searchParams.steelGrade" placeholder="请选择" clearable class="custom-select">
            <el-option label="SPCC-Z" value="SPCC-Z" />
            <el-option label="SPCC-Y" value="SPCC-Y" />
            <el-option label="DC01" value="DC01" />
          </el-select>
        </div>

      </div>
      <div class="search-row">
         <div class="search-item">
          <span class="label">出口卷号</span>
          <el-input v-model="searchParams.exportRollNo" placeholder="请输入" class="custom-input" />
        </div>
        <div class="search-item">
          <span class="label">入口卷号</span>
          <el-input v-model="searchParams.entryRollNo" placeholder="请输入" class="custom-input" />
        </div>
         <div class="search-actions">
          <button class="btn query-btn" @click="handleSearch">查询</button>
          <button class="btn reset-btn" @click="handleReset">重置</button>
          <button class="btn export-btn">导出</button>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 (包含表格+详情 和 列选择器) -->
    <div class="resizable-area-wrapper">
      <!-- 左侧：表格 + 分页 + (可选)详情 -->
      <div class="table-content-wrapper">
        <!-- 上部：表格 + 分页 -->
        <div class="top-panel-wrapper" ref="topPanelRef">
          <div class="table-panel">
            <el-table
              :data="pagedTableData"
              height="100%"
              border
              highlight-current-row
              :row-class-name="tableRowClassName"
              @row-click="selectRow"
              :header-cell-style="{ background: '#2a5caa', color: '#fff', padding: '8px 10px', textAlign: 'center', fontWeight: 'normal', border: 'none' }"
              :cell-style="{ padding: '8px 10px', textAlign: 'center', color: '#c0c4cc', border: 'none' }"
              :row-style="{ background: '#0f2142' }"
            >
             <!-- Columns definition -->
              <el-table-column type="index" label="序号" width="70" align="center" :index="indexMethod" fixed="left" />
              <el-table-column v-if="isColumnVisible('exportRollNo')" prop="exportRollNo" label="酸轧出口卷号" width="160" align="center" />
              <el-table-column v-if="isColumnVisible('entryRollNo')" prop="entryRollNo" label="酸轧入口卷号" width="160" align="center" />
              <el-table-column v-if="isColumnVisible('prodLine')" prop="prodLine" label="产线" width="80" align="center" />
              <el-table-column v-if="isColumnVisible('steelGrade')" prop="steelGrade" label="钢种" width="100" align="center" />
              <el-table-column v-if="isColumnVisible('prodThickness')" prop="prodThickness" label="成品厚度[mm]" width="120" align="center" />
              <el-table-column v-if="isColumnVisible('prodWidth')" prop="prodWidth" label="成品宽度[mm]" width="120" align="center" />
              <el-table-column v-if="isColumnVisible('prodLength')" prop="prodLength" label="成品长度[m]" width="110" align="center" />
              <el-table-column v-if="isColumnVisible('driveSideWave')" prop="driveSideWave" label="传动侧边浪" width="110" align="center" />
              <el-table-column v-if="isColumnVisible('opSideWave')" prop="opSideWave" label="操作侧边浪" width="110" align="center" />
              <el-table-column v-if="isColumnVisible('buckle')" label="翘楚长度[m]" align="center">
                <el-table-column v-if="isColumnVisible('buckleHead')" prop="buckleHead" label="头部" width="80" align="center" />
                <el-table-column v-if="isColumnVisible('buckleBody')" prop="buckleBody" label="本体" width="80" align="center" />
              </el-table-column>
              <el-table-column label="详情" width="180" fixed="right" align="center">
                <template #default="scope">
                  <button class="action-btn rate-btn">评级</button>
                  <button class="action-btn analysis-btn">板形质量分析</button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="pagination-panel">
             <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[10, 30, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pagination.total"
                @size-change="handleSizeChange" 
                @current-change="handleCurrentChange"
                background
              />
          </div>
        </div>

        <!-- 分隔条 (条件渲染) -->
        <div v-if="selectedRow" class="splitter" ref="splitterRef" @mousedown="startDrag"></div>

        <!-- 详情区域 (条件渲染) -->
        <div v-if="selectedRow" class="detail-panel" ref="bottomPanelRef">
            <!-- 统计结果表格 -->
            <div class="detail-section summary-table-section">
              <div class="section-header">统计结果</div>
              <div class="stats-table-container">
                <el-table
                  :data="summaryStatsData"
                  style="width: 100%;"
                  border
                  :header-cell-style="{ background: '#0f2142', color: '#c0c4cc', padding: '6px 8px', textAlign: 'center', fontWeight: 'normal', border: '1px solid #3a5a8a' }"
                  :cell-style="{ background: '#0f2142', color: '#c0c4cc', padding: '6px 8px', textAlign: 'center', border: '1px solid #3a5a8a' }"
                  :row-style="{ background: '#0f2142' }"
                >
                  <el-table-column prop="label" label="" width="100" :cell-style="{ fontWeight: 'bold' }" />
                  <el-table-column prop="class1" label="分级Class1" align="center" />
                  <el-table-column prop="class2" label="分级Class2" align="center" />
                  <el-table-column prop="class3" label="分级Class3" align="center" />
                  <el-table-column prop="class4" label="分级Class4" align="center" />
                  <el-table-column prop="class5" label="分级Class5" align="center" />
                  <el-table-column prop="class6" label="分级Class6" align="center" />
                  <el-table-column prop="class7" label="分级Class7" align="center" />
                </el-table>
              </div>
            </div>

            <!-- 图表区域 (修改为 flex row) -->
            <div class="charts-row"> 
              <div class="detail-section chart-section">
                <div class="section-header">分级class的长度</div>
                <div class="chart-container">
                  <div ref="barChartRef" class="chart-placeholder"></div>
                </div>
              </div>
              <div class="detail-section chart-section">
                <div class="section-header">板形基准IU均值曲线</div>
                <div class="chart-container">
                   <div class="legend" style="text-align: right; margin-bottom: 5px;">
                    <span class="legend-item"><span class="color-box head-max" style="background-color: #5470c6;"></span>IU均值</span>
                    <span class="legend-item"><span class="color-box tail-max" style="background-color: #91cc75;"></span>IU正值</span>
                  </div>
                  <div ref="lineChartRef" class="chart-placeholder"></div>
                </div>
              </div>
              <div class="detail-section chart-section">
                <div class="section-header">单卷分级class的占比</div>
                <div class="chart-container">
                  <div ref="pieChartRef" class="chart-placeholder"></div>
                </div>
              </div>
            </div>
        </div>
      </div>

      <!-- 右侧：列选择器 -->
      <div class="column-selector">
         <el-checkbox 
           v-model="checkAll" 
           :indeterminate="isIndeterminate" 
           @change="handleCheckAllChange"
         >
           全选
         </el-checkbox>
         <el-checkbox-group v-model="visibleColumns" @change="handleCheckedColumnsChange">
           <el-checkbox v-for="col in allColumns" :key="col.prop" :label="col.prop">
             {{ col.label }}
           </el-checkbox>
         </el-checkbox-group>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, onUnmounted, nextTick } from 'vue';
import * as echarts from 'echarts/core';
import {
  BarChart,
  LineChart,
  PieChart
} from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components';
import {
  CanvasRenderer
} from 'echarts/renderers';

// Register ECharts components
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  LineChart,
  PieChart,
  CanvasRenderer
]);

// --- Interfaces --- 
interface SearchParams {
  dateRange: Date[];
  prodThicknessMin: string;
  prodThicknessMax: string;
  prodWidthMin: string;
  prodWidthMax: string;
  materialThicknessMin: string;
  materialThicknessMax: string;
  steelGrade: string;
  exportRollNo: string;
  entryRollNo: string;
}

interface TableRow {
  id: number;
  exportRollNo: string;
  entryRollNo: string;
  prodLine: string;
  steelGrade: string;
  prodThickness: number;
  prodWidth: number;
  prodLength: number;
  driveSideWave: number;
  opSideWave: number;
  buckleHead: number;
  buckleBody: number;
}

interface SummaryStats {
  label: string;
  class1: number;
  class2: number;
  class3: number;
  class4: number;
  class5: number;
  class6: number;
  class7: number;
}

// --- Reactive State --- 
const searchParams = reactive<SearchParams>({
  dateRange: [],
  prodThicknessMin: '',
  prodThicknessMax: '',
  prodWidthMin: '',
  prodWidthMax: '',
  materialThicknessMin: '',
  materialThicknessMax: '',
  steelGrade: '',
  exportRollNo: '',
  entryRollNo: '',
});

// --- Mock Table Data --- 
const allTableData = ref<TableRow[]>(Array.from({ length: 1626 }, (_, i) => ({
  id: i + 1,
  exportRollNo: `L125016${String(52900 - i).padStart(5, '0')}`,
  entryRollNo: `125101${String(7601 + i * 17 % 1000).padStart(5, '0')}`,
  prodLine: `1450`, 
  steelGrade: i % 5 === 0 ? 'SPCC-Y' : (i % 3 === 0 ? 'DC01' : 'SPCC-Z'),
  prodThickness: parseFloat((0.603 + (i % 5 - 2) * 0.001).toFixed(3)),
  prodWidth: 1000 + (i % 10) * 5,
  prodLength: 3584 + (i % 20) * 3,
  driveSideWave: Math.floor(Math.random() * 15) + 1,
  opSideWave: Math.floor(Math.random() * 10) + 1,
  buckleHead: Math.floor(Math.random() * 5),
  buckleBody: Math.floor(Math.random() * 8),
})));

// --- Pagination --- 
const pagination = reactive({
  currentPage: 1,
  pageSize: 30,
  total: allTableData.value.length
});

const pagedTableData = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  const end = start + pagination.pageSize;
  return allTableData.value.slice(start, end);
});

const indexMethod = (index: number) => {
  return (pagination.currentPage - 1) * pagination.pageSize + index + 1;
};

const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.currentPage = 1; // Reset to first page when size changes
};

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
};

// --- Row Selection --- 
const selectedRow = ref<TableRow | null>(null);

const selectRow = (row: TableRow) => {
  selectedRow.value = row;
  console.log('选中行:', row);
};

const tableRowClassName = ({ row }: { row: TableRow }) => {
  if (selectedRow.value && row.id === selectedRow.value.id) {
    return 'selected-row'; 
  }
  return '';
};

// --- Mock Detail Data --- 
const summaryStatsData = computed<SummaryStats[]>(() => {
  if (!selectedRow.value) return [];
  // Generate mock data based on selected row id for variety
  const seed = selectedRow.value.id;
  return [
    {
      label: '长度(m)',
      class1: 8 + (seed % 10),
      class2: 647 + (seed % 50),
      class3: 11852 + (seed % 100),
      class4: 8618 + (seed % 80),
      class5: 300 + (seed % 30),
      class6: 4 + (seed % 5),
      class7: 15 + (seed % 20),
    }
  ];
});

// --- ECharts Refs and Instances ---
const barChartRef = ref<HTMLElement | null>(null);
const lineChartRef = ref<HTMLElement | null>(null);
const pieChartRef = ref<HTMLElement | null>(null);

let barChartInstance: echarts.ECharts | null = null;
let lineChartInstance: echarts.ECharts | null = null;
let pieChartInstance: echarts.ECharts | null = null;

// --- Mock Chart Data Generators ---
const generateBarData = (seed: number) => {
  return summaryStatsData.value[0] 
    ? Object.entries(summaryStatsData.value[0])
        .filter(([key]) => key.startsWith('class'))
        .map(([key, value]) => value + (seed % 100)) // Add variation
    : [];
};

const generateLineData = (seed: number) => {
  const iuMean = Array.from({ length: 20 }, (_, i) => parseFloat((40 + Math.sin(i / 3 + seed / 100) * 10 + Math.random() * 4 - 2).toFixed(1)));
  const iuPositive = iuMean.map(val => parseFloat(Math.max(0, val + Math.random() * 6 - 3).toFixed(1)));
  return { iuMean, iuPositive };
};

const generatePieData = (seed: number) => {
  const baseData = summaryStatsData.value[0] 
    ? Object.entries(summaryStatsData.value[0])
        .filter(([key]) => key.startsWith('class'))
        .map(([key, value], index) => ({ 
            name: `Class ${index + 1}`, 
            value: value + (seed % 100) 
          }))
    : [];
  // Ensure total is not zero for percentage calculation later if needed
  return baseData.filter(item => item.value > 0);
};

// --- ECharts Options ---
const barChartOption = computed(() => {
  if (!selectedRow.value) return {};
  const data = generateBarData(selectedRow.value.id);
  return {
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: [{ type: 'category', data: ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7'], axisTick: { alignWithLabel: true }, axisLabel: { color: '#c0c4cc' } }],
    yAxis: [{ type: 'value', axisLabel: { color: '#c0c4cc' }, splitLine: { lineStyle: { color: '#3a5a8a' } } }],
    series: [{
      name: '长度(m)',
      type: 'bar',
      barWidth: '60%',
      data: data,
      itemStyle: { color: '#2979ff' }
    }]
  };
});

const lineChartOption = computed(() => {
  if (!selectedRow.value) return {};
  const { iuMean, iuPositive } = generateLineData(selectedRow.value.id);
  return {
    tooltip: { trigger: 'axis' },
    legend: { show: false }, // Using custom legend
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', boundaryGap: false, data: Array.from({ length: 20 }, (_, i) => `p${i}`), axisLabel: { color: '#c0c4cc' } },
    yAxis: { type: 'value', axisLabel: { color: '#c0c4cc' }, splitLine: { lineStyle: { color: '#3a5a8a' } } },
    series: [
      { name: 'IU均值', type: 'line', smooth: true, data: iuMean, itemStyle: { color: '#5470c6' } },
      { name: 'IU正值', type: 'line', smooth: true, data: iuPositive, itemStyle: { color: '#91cc75' } }
    ]
  };
});

const pieChartOption = computed(() => {
  if (!selectedRow.value) return {};
  const data = generatePieData(selectedRow.value.id);
  return {
    tooltip: { trigger: 'item', formatter: '{b} : {c} ({d}%)' },
    legend: { 
      orient: 'vertical', 
      left: 'left', 
      textStyle: { color: '#c0c4cc' } 
    },
    series: [{
      name: 'Class占比',
      type: 'pie',
      radius: '70%',
      center: ['60%', '50%'], // Adjust center to avoid legend overlap
      data: data,
      emphasis: {
        itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' }
      },
      label: { color: '#c0c4cc' },
      labelLine: { lineStyle: { color: '#c0c4cc' } }
    }]
  };
});

// --- Chart Initialization and Updates ---
const initCharts = () => {
  try {
    if (barChartRef.value && !barChartInstance) {
      barChartInstance = echarts.init(barChartRef.value);
      barChartInstance.setOption(barChartOption.value);
    }
    if (lineChartRef.value && !lineChartInstance) {
      lineChartInstance = echarts.init(lineChartRef.value);
      lineChartInstance.setOption(lineChartOption.value);
    }
    if (pieChartRef.value && !pieChartInstance) {
      pieChartInstance = echarts.init(pieChartRef.value);
      pieChartInstance.setOption(pieChartOption.value);
    }
  } catch (error) {
    console.error("ECharts initialization failed:", error);
  }
};

const updateCharts = () => {
  if (!selectedRow.value) return;
  try {
    barChartInstance?.setOption(barChartOption.value);
    lineChartInstance?.setOption(lineChartOption.value);
    pieChartInstance?.setOption(pieChartOption.value);
  } catch (error) {
    console.error("ECharts update failed:", error);
  }
};

// Watch for selected row changes to update charts
watch(selectedRow, (newVal) => {
  if (newVal) {
    nextTick(() => {
      initCharts();
      updateCharts();
    });
  }
});

// --- Resize Handling ---
const resizeCharts = () => {
  barChartInstance?.resize();
  lineChartInstance?.resize();
  pieChartInstance?.resize();
};

onMounted(() => {
  window.addEventListener('resize', resizeCharts);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeCharts);
  barChartInstance?.dispose();
  lineChartInstance?.dispose();
  pieChartInstance?.dispose();
});

// --- Handlers --- 
const handleSearch = () => {
  console.log('查询参数:', searchParams);
  // Add actual search logic here, potentially filtering allTableData
  // For now, just log
};

const handleReset = () => {
  Object.keys(searchParams).forEach(key => {
    const typedKey = key as keyof SearchParams;
    if (typedKey === 'dateRange') {
      searchParams[typedKey] = [];
    } else {
      searchParams[typedKey] = '';
    }
  });
  selectedRow.value = null; // Clear selection on reset
  console.log('重置参数');
};

// --- Column Visibility --- 
interface ColumnOption {
  prop: keyof TableRow | 'buckle'; // 'buckle' for the group
  label: string;
}

// Define all possible columns (excluding index and actions)
const allColumns = ref<ColumnOption[]>([
  { prop: 'exportRollNo', label: '酸轧出口卷号' },
  { prop: 'entryRollNo', label: '酸轧入口卷号' },
  { prop: 'prodLine', label: '产线' },
  { prop: 'steelGrade', label: '钢种' },
  { prop: 'prodThickness', label: '成品厚度[mm]' },
  { prop: 'prodWidth', label: '成品宽度[mm]' },
  { prop: 'prodLength', label: '成品长度[m]' },
  { prop: 'driveSideWave', label: '传动侧边浪' },
  { prop: 'opSideWave', label: '操作侧边浪' },
  // Representing the group - visibility controlled by children
  // { prop: 'buckle', label: '翘楚长度[m]' }, 
  { prop: 'buckleHead', label: '翘楚长度-头部[m]' },
  { prop: 'buckleBody', label: '翘楚长度-本体[m]' },
]);

// Default visible columns (adjust as needed)
const defaultVisible = allColumns.value.map(col => col.prop);
const visibleColumns = ref<Array<keyof TableRow | 'buckle'>>([...defaultVisible]);

const checkAll = ref(true);
const isIndeterminate = ref(false);

const isColumnVisible = (prop: keyof TableRow | 'buckle') => {
  // Special handling for the group column header
  if (prop === 'buckle') {
    return visibleColumns.value.includes('buckleHead') || visibleColumns.value.includes('buckleBody');
  }
  return visibleColumns.value.includes(prop);
};

const handleCheckAllChange = (val: boolean) => {
  visibleColumns.value = val ? allColumns.value.map(c => c.prop) : [];
  isIndeterminate.value = false;
};

const handleCheckedColumnsChange = (value: Array<keyof TableRow | 'buckle'>) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === allColumns.value.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < allColumns.value.length;
};

// --- Refs for DOM elements (including splitter logic refs) ---
const topPanelRef = ref<HTMLDivElement | null>(null);
const splitterRef = ref<HTMLDivElement | null>(null);
const bottomPanelRef = ref<HTMLDivElement | null>(null); // Keep for potential future use

// --- State for dragging ---
const isDragging = ref(false);
const startY = ref(0);
const initialTopHeight = ref(0);

// --- Dragging Logic (Copied from ThicknessJudge) ---
const startDrag = (event: MouseEvent) => {
  if (!topPanelRef.value) return;
  isDragging.value = true;
  startY.value = event.clientY;
  initialTopHeight.value = topPanelRef.value.offsetHeight;
  document.body.style.userSelect = 'none'; 
  document.body.style.cursor = 'row-resize'; 

  window.addEventListener('mousemove', doDrag);
  window.addEventListener('mouseup', stopDrag);
};

const doDrag = (event: MouseEvent) => {
  if (!isDragging.value || !topPanelRef.value) return;

  const deltaY = event.clientY - startY.value;
  let newHeight = initialTopHeight.value + deltaY;

  const minHeight = 150; 
  const containerHeight = (topPanelRef.value.parentElement as HTMLElement)?.offsetHeight || window.innerHeight; // Parent is now table-content-wrapper
  const splitterHeight = splitterRef.value?.offsetHeight || 8;
  const bottomMinHeight = 150; 
  const maxHeight = containerHeight - splitterHeight - bottomMinHeight;

  if (newHeight < minHeight) newHeight = minHeight;
  if (newHeight > maxHeight) newHeight = maxHeight;
  
  topPanelRef.value.style.height = `${newHeight}px`;
};

const stopDrag = () => {
  if (!isDragging.value) return;
  isDragging.value = false;
  document.body.style.userSelect = ''; 
  document.body.style.cursor = ''; 

  window.removeEventListener('mousemove', doDrag);
  window.removeEventListener('mouseup', stopDrag);
};

</script>

<style scoped>
/* --- Global Styles (Mostly copied) --- */
.layout-judge-container {
  background-color: #0a1a3a; 
  color: #c0c4cc; 
  padding: 15px;
  height: 100vh; 
  box-sizing: border-box;
  font-family: 'Microsoft YaHei', 'Segoe UI', sans-serif;
  font-size: 13px;
  overflow: hidden; 
  scrollbar-width: thin;
  scrollbar-color: #3a5a8a #142a52;
  display: flex;
  flex-direction: column;
}

.layout-judge-container > *:not(:last-child):not(.detail-section) { 
  margin-bottom: 15px;
}

.layout-judge-container::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.layout-judge-container::-webkit-scrollbar-track {
  background: #142a52;
  border-radius: 3px;
}

.layout-judge-container::-webkit-scrollbar-thumb {
  background-color: #3a5a8a;
  border-radius: 3px;
}

.layout-judge-container::-webkit-scrollbar-thumb:hover {
  background-color: #5a7aa4;
}

/* --- Search Panel (Copied) --- */
.search-panel {
  background-color: #1c2d5a;
  padding: 10px 15px;
  border-radius: 3px;
  flex-shrink: 0;
}

.search-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 10px;
}

.search-row:last-child {
  margin-bottom: 0;
}

.search-item {
  display: flex;
  align-items: center;
  margin-right: 15px; /* Adjusted margin */
  margin-bottom: 10px; /* Added margin for wrapping */
}

.label {
  color: #c0c4cc;
  margin-right: 8px;
  white-space: nowrap;
  min-width: 65px; /* Adjusted width */
  text-align: right;
}

:deep(.custom-date-picker.el-date-editor) {
  width: 260px !important;
  height: 28px;
  background-color: #0a1a3a;
  border: 1px solid #3a5a8a;
  box-shadow: none;
}

:deep(.custom-date-picker .el-range-input),
:deep(.custom-date-picker .el-range-separator) {
  color: #c0c4cc;
  font-size: 13px;
  height: 26px;
  line-height: 26px;
}

:deep(.custom-date-picker .el-range-separator) {
  padding: 0;
}

:deep(.custom-date-picker .el-input__icon) {
  line-height: 28px;
  color: #c0c4cc;
}

.range-item .label {
  min-width: 65px; /* Adjusted width */
}

.range-input {
  width: 80px;
}

:deep(.range-input .el-input__wrapper) {
  padding-left: 8px;
  padding-right: 8px;
}

.separator {
  margin: 0 5px;
  color: #c0c4cc;
}

.custom-input,
.custom-select,
.range-input,
:deep(.el-input__wrapper),
:deep(.el-select__wrapper) {
  height: 28px;
  line-height: 28px;
  background-color: #0a1a3a !important;
  border: 1px solid #3a5a8a !important;
  border-radius: 3px !important;
  color: #c0c4cc !important;
  box-shadow: none !important;
  font-size: 13px !important;
}

:deep(.el-input__inner) {
  color: #c0c4cc !important;
  height: 26px !important;
  line-height: 26px !important;
}

:deep(.custom-select .el-select__placeholder),
:deep(.custom-select .el-select__caret) {
  color: #c0c4cc;
}

.custom-input {
  width: 150px;
}

.custom-select {
  width: 120px; /* Adjusted width */
}

.search-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
  padding-left: 20px; /* Ensure spacing */
}

.btn {
  height: 28px;
  padding: 0 15px;
  border: none;
  border-radius: 3px;
  font-size: 13px;
  cursor: pointer;
  margin-left: 10px;
  color: #fff;
}

.query-btn {
  background-color: #2979ff;
}
.query-btn:hover {
  background-color: #5393ff;
}

.reset-btn {
  background-color: #3a5a8a;
}
.reset-btn:hover {
   background-color: #5a7aa4;
}

.export-btn {
  background-color: #2979ff;
}
.export-btn:hover {
  background-color: #5393ff;
}

/* --- Main Layout Wrappers --- */
.resizable-area-wrapper {
  display: flex;
  flex-grow: 1;
  min-height: 0; /* Important for flex shrinking */
  gap: 10px; /* Add gap between table area and selector */
}

.table-content-wrapper {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  min-width: 0; /* Allow shrinking */
  overflow: hidden; /* Contain splitter and panels */
}

/* --- Top Panel (Table + Pagination) --- */
.top-panel-wrapper {
  display: flex;
  flex-direction: column;
  /* height: 60%; */ /* Initial height, can be adjusted */
  flex-basis: 60%; /* Use flex-basis for initial size */
  min-height: 200px; /* Min height */
  overflow: hidden; 
}

.table-panel {
  flex-grow: 1; 
  min-height: 0;
  overflow: auto; /* Enable scrollbars for table content */
  /* background/padding from previous styles */
  background-color: #1c2d5a;
  padding: 5px;
  border-radius: 3px;
  display: flex; /* Keep display: flex if needed by el-table internal */
}

/* Ensure el-table itself doesn't force 100% width */
:deep(.table-panel .el-table) {
  /* Maybe remove width: 100% if it exists implicitly? */
}

.pagination-panel {
  flex-shrink: 0;
  /* Styles copied */
  background-color: #1c2d5a;
  padding: 8px 15px;
  border-radius: 3px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

/* --- Splitter (Copied) --- */
.splitter {
  height: 8px;
  background-color: #3a5a8a; 
  cursor: row-resize;
  flex-shrink: 0; 
  border-top: 1px solid #5a7aa4;
  border-bottom: 1px solid #5a7aa4;
}
.splitter:hover {
  background-color: #5a7aa4; 
}

/* --- Detail Panel (Copied/Adjusted) --- */
.detail-panel {
  flex: 1; /* Grow to fill remaining space */
  min-height: 150px; 
  overflow: auto; 
  /* padding-top: 15px; */ /* Remove padding if splitter provides separation */
  /* border-top: 1px solid #3a5a8a; */ /* Remove border if splitter provides separation */
}

/* --- Column Selector (New Position) --- */
.column-selector {
  flex-shrink: 0;
  width: 180px; /* Adjust width as needed */
  background-color: #1c2d5a; /* Match panel background */
  border: 1px solid #3a5a8a;
  border-radius: 4px;
  padding: 10px 15px;
  overflow-y: auto;
  height: 100%; /* Take full height of the wrapper */
  box-sizing: border-box;
  scrollbar-width: thin;
  scrollbar-color: #3a5a8a #142a52;
}
/* ... Rest of column selector styles (checkboxes etc copied) ... */
.column-selector::-webkit-scrollbar { /* ... */ }
.column-selector::-webkit-scrollbar-track { /* ... */ }
.column-selector::-webkit-scrollbar-thumb { /* ... */ }
.column-selector .el-checkbox-group { /* ... */ }
.column-selector .el-checkbox { /* ... */ }
:deep(.column-selector .el-checkbox__label) { /* ... */ }
:deep(.column-selector .el-checkbox__inner) { /* ... */ }
:deep(.column-selector .el-checkbox__input.is-checked .el-checkbox__inner), 
:deep(.column-selector .el-checkbox__input.is-indeterminate .el-checkbox__inner) { /* ... */ }


/* --- Copied Styles (Ensure consistency) --- */
:deep(.el-table) { /* ... */ }
:deep(.el-table__header-wrapper th.el-table__cell) { /* ... */ }
:deep(.el-table__body td.el-table__cell) { /* ... */ }
:deep(.el-table__body tr.current-row > td.el-table__cell), 
:deep(.el-table__body tr.selected-row > td.el-table__cell) { /* ... */ }
.action-btn { /* ... */ }
/* ... pagination styles ... */
.summary-table-section { /* ... */ }
.chart-sections-wrapper { /* ... */ }
.detail-section { /* ... */ }
.section-header { /* ... */ }
.stats-table-container { /* ... */ }
.stats-table-container :deep(.el-table) { /* ... */ }
.chart-container { /* ... */ }
.legend { /* ... */ }
.chart-placeholder { /* ... */ }

/* Ensure chart placeholders have height */
.chart-placeholder {
  min-height: 200px; 
  height: 100%;
  width: 100%;
}

/* --- Ensure Button Styles are Present --- */
.action-btn {
  padding: 3px 8px;
  font-size: 12px;
  border: none;
  border-radius: 3px;
  margin: 0 2px;
  cursor: pointer;
  color: #fff;
}
.rate-btn { background-color: #e6a23c; }
.rate-btn:hover { background-color: #ebb563; }
.analysis-btn { background-color: #67c23a; }
.analysis-btn:hover { background-color: #85ce61; }

/* --- Ensure Selected Row Styles are Present --- */
:deep(.el-table__body tr.current-row > td.el-table__cell),
:deep(.el-table__body tr.selected-row > td.el-table__cell) { 
  background-color: #263451 !important;
  color: #fff !important;
}
:deep(.el-table__body tr.current-row > td.el-table-column--fixed-right),
:deep(.el-table__body tr.selected-row > td.el-table-column--fixed-right) {
   background-color: #263451 !important;
}

/* --- Detail Panel --- */
.detail-panel {
  /* ... existing styles ... */
}

.summary-table-section {
  /* ... existing styles ... */
}

/* Removed .chart-sections-wrapper grid styles */
/* New styles for horizontal chart layout */
.charts-row {
  display: flex;
  gap: 15px; 
  margin-top: 15px; /* Add margin above the chart row */
}

.chart-section { /* Style for individual chart sections in the row */
  flex: 1;
  min-width: 0; /* Allow shrinking */
  /* Keep existing .detail-section styles like background, border-radius */
  background-color: #1c2d5a;
  border-radius: 3px;
  overflow: hidden;
  display: flex; /* Ensure header and chart container stack vertically */
  flex-direction: column;
}

.chart-container {
   /* ... existing styles ... */
   flex-grow: 1; /* Allow chart container to fill vertical space */
}

.chart-placeholder {
  /* ... existing styles ... */
}

/* ... Rest of styles ... */
</style>
